<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="门店名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select 
        v-model="listQuery.status" 
        placeholder="门店状态" 
        clearable 
        class="filter-item" 
        style="width: 130px"
      >
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增门店
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="门店名称" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="地址" min-width="200px">
        <template slot-scope="{row}">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="联系电话" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.contact }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="营业时间" width="180" align="center">
        <template slot-scope="{row}">
          <span>{{ row.businessHours }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '营业中' : '已停业' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button 
            v-if="row.status === 0" 
            size="mini" 
            type="success" 
            @click="handleModifyStatus(row, 1)"
          >
            开业
          </el-button>
          <el-button 
            v-else
            size="mini" 
            type="warning" 
            @click="handleModifyStatus(row, 0)"
          >
            停业
          </el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-show="total > 0"
      :current-page="listQuery.current"
      :page-sizes="[5, 10, 20, 30, 50]"
      :page-size="listQuery.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑门店对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="门店名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入门店名称" />
        </el-form-item>
        
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" placeholder="请输入门店地址" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contact">
          <el-input v-model="temp.contact" placeholder="请输入联系电话" />
        </el-form-item>
        
        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="temp.businessHours" placeholder="例如：9:00-22:00" />
        </el-form-item>
        
        <el-form-item label="营业状态" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="0">停业</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="门店描述">
          <el-input
            v-model="temp.description"
            type="textarea"
            :rows="3"
            placeholder="请输入门店描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchStores, createStore, updateStore, deleteStore, updateStoreStatus } from '@/api/modules/app/store'

export default {
  name: 'StoreManagement',
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        name: undefined,
        status: undefined
      },
      statusOptions: [
        { label: '营业中', value: 1 },
        { label: '已停业', value: 0 }
      ],
      temp: {
        id: undefined,
        name: '',
        address: '',
        contact: '',
        businessHours: '',
        status: 1,
        description: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑门店',
        create: '新增门店'
      },
      rules: {
        name: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
        contact: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
        businessHours: [{ required: true, message: '营业时间不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchStores(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        
        // 设置表格加载状态结束
        setTimeout(() => {
          this.listLoading = false
        }, 300)
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        address: '',
        contact: '',
        businessHours: '',
        status: 1,
        description: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createStore(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建门店成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateStore(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新门店成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleModifyStatus(row, status) {
      const statusText = status === 1 ? '开业' : '停业'
      this.$confirm(`确认要将该门店设为${statusText}状态吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStoreStatus(row.id, { status }).then(() => {
          this.$notify({
            title: '成功',
            message: '状态修改成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该门店, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStore(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(size) {
      this.listQuery.size = size
      this.getList()
    },
    handleCurrentChange(current) {
      this.listQuery.current = current
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
}
</style>